<template>
  <div class="products-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">产品中心</h1>
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>产品中心</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    
    <div class="products-layout">
      <!-- 修改产品筛选区域 -->
      <div class="filter-sidebar">
        <h3 class="filter-title">产品分类</h3>
        <div class="category-list">
          <div 
            v-for="category in categoryData" 
            :key="category.id"
            class="category-item"
            :class="{ active: selectedCategory === category.id }"
            @click="handleCategoryClick(category)"
          >
            {{ category.name }}
          </div>
        </div>
      </div>

      <!-- 产品展示区域 -->
      <div class="products-content">
        <div class="products-toolbar">
          <div class="search-box">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索产品"
              prefix-icon="Search"
              @input="handleSearch"
            />
          </div>
          <div class="sort-options">
            <el-radio-group v-model="sortOption" size="small" @change="handleSortChange">
              <el-radio-button label="newest">最新</el-radio-button>
              <el-radio-button label="popular">热门</el-radio-button>
            </el-radio-group>
          </div>
        </div>

        <!-- 产品列表 -->
        <div v-loading="loading" class="products-grid">
          <el-empty v-if="filteredProducts.length === 0" description="暂无产品" />
          <div
            v-for="product in filteredProducts"
            :key="product.id"
            class="product-card"
            @click="goToProductDetail(product.id)"
          >
            <div class="product-image">
              <el-image
                :src="product.image"
                fit="cover"
                :preview-src-list="[product.image]"
                loading="lazy"
              >
                <template #error>
                  <div class="image-placeholder">
                    <el-icon><Picture /></el-icon>
                  </div>
                </template>
              </el-image>
            </div>
            <div class="product-info">
              <h3 class="product-title">{{ product.name }}</h3>
              <p class="product-desc">{{ product.description }}</p>
              <el-button type="primary" size="small" class="view-btn">查看详情</el-button>
            </div>
          </div>
        </div>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[12, 24, 36, 48]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalProducts"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'nuxt/app'
import { ElMessage } from 'element-plus'
import { Picture } from '@element-plus/icons-vue'
import {getProductCategory, getProductList} from "~/api/product";

const router = useRouter()

// 产品数据
const products = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(12)
const totalProducts = ref(0)
const searchKeyword = ref('')
const selectedCategory = ref(null)
const sortOption = ref('newest')

// 分类数据
const categoryData = ref([
  { id: 0, name: '全部' }
])

// 移除不需要的 defaultProps
// const defaultProps = {
//   children: 'children',
//   label: 'label'
// }

// 过滤后的产品列表
const filteredProducts = computed(() => {
  let result = products.value

  // 按分类筛选
  if (selectedCategory.value && selectedCategory.value !== 0) {
    result = result.filter(item => item.categoryId === selectedCategory.value)
  }

  // 按关键词搜索
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    result = result.filter(
      item =>
        item.name.toLowerCase().includes(keyword) ||
        (item.description && item.description.toLowerCase().includes(keyword))
    )
  }

  return result
})

// 获取产品数据
const fetchProducts = async () => {
  loading.value = true
  try {
    const res = await getProductList({
      pageNo: currentPage.value,
      pageSize: pageSize.value,
      sort: sortOption.value,
      keyword: searchKeyword.value,
      categoryId: selectedCategory.value
    })
      products.value = res.lists
      totalProducts.value = res.count
  } catch (error) {
    console.error('获取产品列表出错:', error)
    ElMessage.error('获取产品列表失败')
  } finally {
    loading.value = false
  }
}

// 获取分类数据
const fetchCategories = async () => {
  try {
    const res = await getProductCategory()
    console.log('分类数据:', res)
    // 将后端返回的分类数据添加到categoryData中
    categoryData.value = [
      { id: 0, name: '全部' },
      ...res.list
    ]
  } catch (error) {
    console.error('获取分类出错:', error)
    ElMessage.error('获取分类失败')
  }
}

// 处理分类点击
const handleCategoryClick = (data) => {
  selectedCategory.value = data.id
  currentPage.value = 1
  fetchProducts()
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchProducts()
}

// 处理排序变化
const handleSortChange = () => {
  currentPage.value = 1
  fetchProducts()
}

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchProducts()
}

// 处理每页数量变化
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  fetchProducts()
}

// 跳转到产品详情页
const goToProductDetail = (id) => {
  router.push(`/products/${id}`)
}

// 页面加载时获取数据
onMounted(() => {
  fetchCategories()
  fetchProducts()
})
</script>

<style lang="scss" scoped>
.products-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.page-header {
  margin-bottom: 30px;
}

.page-title {
  font-size: 28px;
  color: #333;
  margin: 0 0 15px;
}

.products-layout {
  display: flex;
  gap: 30px;
}

.filter-sidebar {
  width: 200px;
  flex-shrink: 0;
  background: #fff;
  border-radius: 8px;
  padding: 0;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  align-self: flex-start;
  position: sticky;
  top: 20px;
  overflow: hidden;
}

.filter-title {
  font-size: 16px;
  padding: 15px 20px;
  margin: 0;
  color: #fff;
  background-color: var(--el-color-primary);
  font-weight: 500;
}

.category-list {
  .category-item {
    padding: 12px 20px;
    font-size: 14px;
    color: #333;
    cursor: pointer;
    transition: all 0.3s ease;
    border-bottom: 1px solid #f0f0f0;
    position: relative;
    
    &:hover {
      color: var(--el-color-primary);
      background-color: #f6f9ff;
      padding-left: 25px;
    }
    
    &.active {
      color: var(--el-color-primary);
      background-color: #f6f9ff;
      font-weight: 500;
      padding-left: 25px;
      
      &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 0;
        width: 4px;
        height: 100%;
        background-color: var(--el-color-primary);
      }
    }
    
    &:last-child {
      border-bottom: none;
    }
  }
}

.filter-title {
  font-size: 18px;
  margin-bottom: 5px;
  color: #ffffff;
  font-weight: 600;
  position: relative;
  padding-left: 12px;
  
  &::before {
    content: '';
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
    width: 3px;
    height: 16px;
    background-color: var(--el-color-primary);
    border-radius: 1.5px;
  }
}

.products-content {
  flex: 1;
}

.products-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-box {
  width: 300px;
}

.products-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(270px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
  min-height: 400px;
}

.product-card {
  background: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  transition: transform 0.3s, box-shadow 0.3s;
  cursor: pointer;

  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
  }
}

.product-image {
  height: 200px;
  overflow: hidden;
  
  .el-image {
    width: 100%;
    height: 100%;
  }
  
  .image-placeholder {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;
    background: #f5f7fa;
    
    .el-icon {
      font-size: 40px;
      color: #909399;
    }
  }
}

.product-info {
  padding: 15px;
}

.product-title {
  font-size: 16px;
  margin: 0 0 10px;
  color: #333;
  font-weight: 600;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.product-desc {
  font-size: 14px;
  color: #666;
  margin: 0 0 15px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  height: 40px;
}

.view-btn {
  width: 100%;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

@media (max-width: 768px) {
  .products-layout {
    flex-direction: column;
  }
  
  .filter-sidebar {
    width: 100%;
    position: static;
  }
  
  .search-box {
    width: 100%;
  }
  
  .products-toolbar {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
}
</style>